$(document).ready(function() {
	var suser_id;
	var suser_name;
	var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPUASGRP : "XPUASGRP",
        T_XPUASGFN : "XPUASGFN",
        T_XPLSTDAT : "XPLSTDAT"
	}
	/**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                  : $(window)             ,
        userID             : $("#userInfoDialog_userIDTxt"),
        userName           : $("#userInfoDialog_userNameTxt"),
        pswd               : $("#userInfoDialog_pswdTxt"),
        userInfoDialog     : $("#userInfoDialog"),
        userIDG            : $("#userFuncGroupDialog_userIDGTxt"),
        userNameG          : $("#userFuncGroupDialog_userNameGTxt"),
        userFncGroupDialog : $("#userFuncGroupDialog"),
        queryUserDialog    : $("#queryUserDialog"),
        queryUserID        : $("#queryUserDialog_userIDTxt"),
        mainGrd   :{
            grdId     : $("#userInfoGrd")   ,
            grdPgText : "#userInfoPg"       ,
            fatherDiv : $("#userInfoDiv")
        },
        fncGrpGrd:{
        	grdId     : $("#userFncGroupGrd"),
        	grdPgText : "#userFncGroupPg"    ,
        	fatherDiv : $("#userFncGroupDiv")
        }
    };
        /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        f5 : $("#f5_btn"),
        f6 : $("#f6_btn"),
        f1 : $("#f1_query_btn"),
        f9 : $("#f9_btn"),
        execute: $("#userInfoDialog_executeBtn"),
        cancel: $("#userInfoDialog_cancelBtn"),
        register:$("#userFuncGroupDialog_executeBtn"),
        query: $("#queryUserDialog_queryBtn")
    };
   var iniGridInfo = {
   		iniUserGridInfo:function(){
   			var grdInfoCM = [
	            {name: 'usr_id'  , index: 'usr_id'  , label: USER_ID_TAG   , sortable: true, width: USR_ID_CLM},
	            {name: 'usr_name', index: 'usr_name', label: USER_NAME_TAG    , sortable: false, width: USR_NAME_CLM}
    		];
	        controlsQuery.mainGrd.grdId.jqGrid({
	              url:"",
			      datatype:"local",
			      mtype:"POST",
			      // height:400,//TODO:需要根据页面自适应，要相对很高
			      // width:"99%",
			      autowidth:true,//宽度根据父元素自适应
			      height:400,
			      shrinkToFit:true,
			      scroll:false,
			      resizable : true,
			      loadonce:true,
			      // toppager: true , 翻页控件是否在上层显示
			      fixed: true,
			      // hidedlg:true,
			      jsonReader : {
			            // repeatitems: false
			          },
			      viewrecords : true, //显示总记录数
			      rownumbers  :true ,//显示行号
			      rowNum:50,         //每页多少行，用于分页
			      rownumWidth : 40,  //行号列宽度
			      emptyrecords :true ,
			      pginput  : true ,//可以输入跳转页数
			      rowList:[5,10,20,50], //每页多少行
//			      toolbar : [true, "top"],//显示工具列 : top,buttom,both
		          pager : controlsQuery.mainGrd.grdPgText,
		          colModel: grdInfoCM
//                  ondblClickRow : function(id) {	 
//                	  btnFunc.f9_func();
//                  }
	        });
		 }, iniFuncGridInfo:function(){
			 	var grdInfoCM = [
		 		{name: 'data_id' , index: 'data_id'  , label: DATA_ID_TAG           , sortable: true, width: DATA_ID_CLM},
	            {name: 'ext_1'   , index: 'ext_1'    , label: GROUP_ID_TAG          , sortable: true, width: EXT_1_CLM},
	            {name: 'ext_2'   , index: 'ext_2'    , label: GROUP_NAME_TAG        , sortable: false, width: EXT_2_CLM},
	            {name: 'data_ext', index: 'data_ext' , label: DATA_EXT_TAG         , sortable: false, width: DATA_EXT_CLM},
	            {name: 'ext_3'   , index: 'ext_3'    , label: ADMINISTRATOR_FLAG_TAG, sortable: false, width: EXT_3_CLM}
    		];
    		controlsQuery.fncGrpGrd.grdId.jqGrid({
	              url:"",
			      datatype:"local",
			      mtype:"POST",
			      autowidth:true,//宽度根据父元素自适应
			      height:400,
			      shrinkToFit:true,
			      scroll:false,
			      resizable : true,
			      loadonce:true,
			      // toppager: true , 翻页控件是否在上层显示
			      fixed: true,
			      multiselect : true,
			      jsonReader : {
		            // repeatitems: false
		          },
			      rownumbers  :true ,//显示行号
			      rowNum:500,         //每页多少行，用于分页
		          colModel: grdInfoCM
	        });
		 }
   };
        /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
    	UserDialogShowFnc:function(){
			$("input").val("");
			controlsQuery.userID.val("");
			controlsQuery.userID.focus();
			controlsQuery.userName.val("");
			controlsQuery.pswd.val("");
			controlsQuery.userID.attr("disabled",false);
		},UserDialogShowUFnc:function(){
			var crGrid;
			crGrid = controlsQuery.mainGrd.grdId;
			var rowid  = crGrid.jqGrid('getGridParam','selrow');
			if( rowid == null){
				controlsQuery.userInfoDialog.modal("hide");
				showErrorDialog("请选择需要更新的用户!");
				return false;
			}
			var data = crGrid.jqGrid('getRowData',rowid);
			$.post('jcom/checkUserAdmin', {
			}, function(Autdata) {
				if( Autdata== false){
					if(data['usr_id']!=VAL.EVT_USER){
						showErrorDialog("","你没有权限更改别人的密码!");
						controlsQuery.userInfoDialog.modal("hide");
						return false;
					}
				}
			});
			$("input").val("");
			controlsQuery.userID.val(data['usr_id']);
			controlsQuery.userName.val(data['usr_name']);
			controlsQuery.pswd.val("");
			controlsQuery.userID.attr("disabled",true);
			controlsQuery.userName.attr("disabled",true);
			controlsQuery.pswd.focus();
		},showUserFncGroupDialogFnc:function(userID,userName){
			var inObj,
				outObj,
				rowIDs,
				crGrid,
				rowData;
			var iary = {
        		data_cate  : 'UFGP'
    		};
		    var inObj = {
		         trx_id     : VAL.T_XPLSTDAT ,
		         action_flg : 'Q'        ,
		         iary       : iary
		     };
		     var  outTrxObj = comTrxSubSendPostJson(inObj);
	         if(  outTrxObj.rtn_code != VAL.NORMAL ) {
	            return false;
	   	     }
	   	     setGridInfo(outTrxObj.oary,"#userFncGroupGrd");
	   	     var iary = {
		   	      data_cate  : 'UFUG',
		   	      data_ext: userID
	   	     };
	   	     var inObj = {
		         trx_id     : VAL.T_XPLSTDAT ,
		         action_flg : 'Q'        ,
		         iary       : iary
		     };
		     var  UseroutTrxObj = comTrxSubSendPostJson(inObj);
	         if(  outTrxObj.rtn_code != VAL.NORMAL ) {
	            return false;
	   	     }
	   	     crGrid = controlsQuery.fncGrpGrd.grdId;
			 rowIDs = crGrid.jqGrid('getDataIDs');
			 if( UseroutTrxObj.tbl_cnt == 1){
			 	for(var intX=0;intX<outTrxObj.tbl_cnt;intX++){
	   	     		rowData = crGrid.jqGrid('getRowData',rowIDs[intX]);
	   	     		if( UseroutTrxObj.oary.data_id == rowData['data_id']){
	   	     			crGrid.setSelection(rowIDs[intX]);
	   	     		}
	   	    	 }
	   	     }else{
				for( var intY=0;intY<UseroutTrxObj.tbl_cnt;intY++ ){
	   	     		for(var intX=0;intX<outTrxObj.tbl_cnt;intX++){
	   	     			rowData = crGrid.jqGrid('getRowData',rowIDs[intX]);
	   	     			if( UseroutTrxObj.oary[intY].data_id == rowData['data_id']){
	   	     				crGrid.setSelection(rowIDs[intX]);
	   	     			}
	   	    	 	}
	   	     	}

	   	     }
	   	     	
			$("input").val("");
			controlsQuery.userIDG.val(userID);
			controlsQuery.userNameG.val(userName);
			
		},AddUserInfo:function(){
			var userID,
				userName,
				pswd,
				inObj,
				outObj,
				month;
			var date = new Date();
			if( date.getMonth()+1 <10){
				month = "0"+(date.getMonth()+1);
			}else{
				month = date.getMonth()+1;
			}
			var strDate = date.getFullYear()+"-"+ month +"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
			if( $.trim(controlsQuery.userID.val()) == ""){
				showErrorDialog("请输入用户代码!");
				return false;
			}
			if( $.trim(controlsQuery.userName.val()) == ""){
				showErrorDialog("请输入用户姓名!");
				return false;
			}
			if( $.trim(controlsQuery.pswd.val()) == ""){
				showErrorDialog("请输入用户密码!");
				return false;
			}
			var iary={
				user_id:controlsQuery.userID.val(),
				user_name:controlsQuery.userName.val(),
				pass_word:controlsQuery.pswd.val(),
				evt_usr:VAL.EVT_USER,
				evt_timestamp: strDate,
				reg_timestamp: strDate
			};
			var inObj={
				trx_id    :VAL.T_XPUASGRP,
				action_flg:'A',
				tbl_cnt:1,
				iary : iary
			};
			outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
            	controlsQuery.userInfoDialog.modal("hide");
                showSuccessDialog("添加成功");
                toolFunc.getUserInfoFnc();
            }else{
                return null;
            }
		},
		
		getUserInfoFnc:function(){
			var inObj,
				outObj;
			var iary = {};
			var QuserID = controlsQuery.queryUserID.val();
			if(QuserID ==""){
				inObj={
					trx_id    :VAL.T_XPUASGRP,
					action_flg:'Q'
				};
			}else{
				iary.usr_id = QuserID;
				inObj ={
		           trx_id     : VAL.T_XPUASGRP ,
		           action_flg : 'Q'        ,   
		           iary       : iary       ,
		           tbl_cnt    : 1
	        	}
			}
			outObj = comTrxSubSendPostJson(inObj);
			if( outObj.rtn_code == VAL.NORMAL){
				if(QuserID ==""){
					$.post('jcom/checkUserAdmin', {
					}, function(Autdata) {
						if( Autdata== false){
							for(var i=0;i<outObj.oary.length;i++){
								if(VAL.EVT_USER == outObj.oary[i].usr_id){
									setGridInfo(outObj.oary[i], "#userInfoGrd" );
									return false;
//									var dataRow={
//										usr_id : outObj.oary[i].usr_id,
//										usr_name : outObj.oary[i].usr_name
//									}
								}
							}
						}else{
							setGridInfo(outObj.oary, "#userInfoGrd" );
				        	controlsQuery.queryUserDialog.modal("hide");
						}
					});
				}else{
					setGridInfo(outObj.oary, "#userInfoGrd" );
		        	controlsQuery.queryUserDialog.modal("hide");
				}
	        	
	        }
		},UpdateUserInfoFnc:function(){
			var userID,
				userName,
				pswd,
				inObj,
				outObj,
				month;
			var date = new Date();
			if( date.getMonth()+1 <10){
				month = "0"+(date.getMonth()+1);
			}else{
				month = date.getMonth()+1;
			}
			var strDate = date.getFullYear()+"-"+ month +"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
			if( $.trim(controlsQuery.userName.val()) == ""){
				showErrorDialog("请输入用户姓名!");
				return false;
			}
			if( $.trim(controlsQuery.pswd.val()) == ""){
				showErrorDialog("请输入用户密码!");
				return false;
			}
			var iary={
				usr_id:controlsQuery.userID.val(),
				usr_key:controlsQuery.pswd.val(),
				evt_usr:VAL.EVT_USER
//				evt_timestamp: strDate
			}
			var inObj={
				trx_id    :VAL.T_XPUASGRP,
				action_flg:'K',
				tbl_cnt:1,
				iary : iary
			}
			outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
            	controlsQuery.userInfoDialog.modal("hide");
                showSuccessDialog("更新成功");
                toolFunc.getUserInfoFnc();
            }else{
                return null;
            }
		},DleteUserInfoFnc:function(user_id){
			var inObj,
				outObj,
				month;
			var date = new Date();
			if( date.getMonth()+1 <10){
				month = "0"+(date.getMonth()+1);
			}else{
				month = date.getMonth()+1;
			}
			var strDate = date.getFullYear()+"-"+ month +"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
			
			var iary={
				usr_id:user_id,
				evt_usr:VAL.EVT_USER
//				evt_timestamp: strDate
			}
			var inObj={
				trx_id    :VAL.T_XPUASGRP,
				action_flg:'D',
				tbl_cnt:1,
				iary : iary
			}
			outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
            	controlsQuery.userInfoDialog.modal("hide");
                showSuccessDialog("删除成功");
                toolFunc.getUserInfoFnc();
            }else{
                return null;
            }
		
		},AddGroupBindUserFnc:function(){
			var rowIDs,
				crGrid,
				//crmGrid,
				//data,
				rowData,
				inObj,
				outObj,
				groupInfo,
				user_id,
    			user_name;
//			crmGrid = controlsQuery.mainGrd.grdId;
//			var rowid  = crmGrid.jqGrid('getGridParam','selrow');
//			if( rowid == null){
//				controlsQuery.userFncGroupDialog.modal("hide");
//				showErrorDialog("请选择用户!");
//				return false;
//			}
//			data = crmGrid.jqGrid('getRowData',rowid);
//			user_id = data['usr_id'];
//			user_name = data['usr_name'];
			crGrid = controlsQuery.fncGrpGrd.grdId;
			rowIDs = crGrid.jqGrid('getGridParam','selarrrow');
			if( rowIDs.length == 0){
				showErrorDialog("请为用户["+controlsQuery.userIDG.val()+"],添加对应的权限组!");
				return false;
			}
			var iaryA = {
				data_cate  : 'UFUG',
				data_ext:suser_id
			}
			var inObj = {
		         trx_id     : VAL.T_XPLSTDAT ,
		         action_flg : 'Q'        ,
		         iary       : iaryA
		     };
		     var outObj = comTrxSubSendPostJson(inObj);
		     if(outObj.rtn_code != VAL.NORMAL){
		     	return;	
		     }
		     if( outObj.tbl_cnt != 0 ){
		     	var iary = new Array();
		     	if(outObj.tbl_cnt == 1){
		     		var gruopData = {data_cate  : 'UFUG', data_ext:suser_id, data_id:outObj.oary.data_id}
		     		iary.push(gruopData);	
		     	}else{
					for(var j=0;j<outObj.tbl_cnt;j++){
			     		var gruopData = {data_cate  : 'UFUG', data_ext:suser_id, data_id:outObj.oary[j].data_id}
			     		iary.push(gruopData);
		     		}
		     	}
				var inObj = {
			         trx_id     : VAL.T_XPLSTDAT ,
			         action_flg : 'D'        ,
			         iary       : iary
			     };
			     var outObj = comTrxSubSendPostJson(inObj);
			     if(outObj.rtn_code != VAL.NORMAL){
			     	return;	
			     }
		     }
		     rowIDs = crGrid.jqGrid('getGridParam','selarrrow');
		     var iary = new Array();
			 for( var i =0;i<rowIDs.length;i++){
				var rowData = crGrid.jqGrid('getRowData',rowIDs[i]);
				var groupInfo = {data_cate:'UFUG',data_id:rowData['data_id'],data_ext:suser_id,
								 ext_1:rowData['ext_1'],ext_2:rowData['ext_2'],ext_3:rowData['ext_3']};
				iary.push(groupInfo);
			 }
		    var inObjG = {
		         trx_id     : VAL.T_XPLSTDAT ,
		         action_flg : 'A'        ,
		         iary       : iary
		     };
		    var outObjG = comTrxSubSendPostJson(inObjG);
		    if(outObjG.rtn_code == VAL.NORMAL){
		    	showSuccessDialog("登记成功");
		    }
		},resetJqgrid:function(){
			var crGrid,fatherDiv;
			crGrid = controlsQuery.mainGrd.grdId;
			fatherDiv = controlsQuery.mainGrd.fatherDiv;
			crGrid.setGridWidth(fatherDiv.width*0.95);
			crGrid.setGridHeight(fatherDiv.height*0.80);
			W.bind("onresize", this);
		},
		userDialogShow:function(){
			controlsQuery.mainGrd.grdId.jqGrid("clearGridData");
    	}
    }
    var btnFunc = {
	   query_func : function(){
    	   toolFunc.userDialogShow();
           controlsQuery.queryUserDialog.modal({
              backdrop:true,
              keyboard:false,
              show:false
           });
           controlsQuery.queryUserDialog.unbind('shown.bs.modal');
           btnQuery.query.unbind('click');
           $('[rel=tooltip]').tooltip({
               placement:"bottom",
               trigger:"focus",
               animation:true
           })
           controlsQuery.queryUserDialog.bind('shown.bs.modal',toolFunc.userDialogShow);
           controlsQuery.queryUserDialog.modal("show");
           btnQuery.query.bind('click',toolFunc.getUserInfoFnc);
           controlsQuery.queryUserID.attr({'disabled':false});
           controlsQuery.queryUserID.focus();
    	},
    	f5_func : function(){
    		toolFunc.UserDialogShowFnc();
			controlsQuery.userInfoDialog.modal({
		        backdrop:true,
		        keyboard:false,
		        show:false
	    	});
		    controlsQuery.userInfoDialog.unbind('shown.bs.modal');
		    btnQuery.execute.unbind('click');
			$('[rel=tooltip]').tooltip({
	          placement:"bottom",
	          trigger:"focus",
	          animation:true
        	})
		    controlsQuery.userInfoDialog.bind('shown.bs.modal',toolFunc.UserDialogShowFnc);
		    controlsQuery.userInfoDialog.modal("show");
		    btnQuery.execute.bind('click',toolFunc.AddUserInfo);
    	},
    	f6_func : function(){
//    		toolFunc.UserDialogShowFnc();
    		controlsQuery.userInfoDialog.modal({
		        backdrop:true,
		        keyboard:false,
		        show:false
	    	});
	    	controlsQuery.userInfoDialog.unbind('shown.bs.modal');
	    	btnQuery.execute.unbind('click');
	    	controlsQuery.userInfoDialog.bind('shown.bs.modal',toolFunc.UserDialogShowUFnc);
	    	controlsQuery.userInfoDialog.modal("show");
	    	btnQuery.execute.bind('click',toolFunc.UpdateUserInfoFnc);
    	},
    	f7_func : function(){
    		var user_id,
    			crGrid,
    			data;
    		crGrid = controlsQuery.mainGrd.grdId;
			var rowid  = crGrid.jqGrid('getGridParam','selrow');
			if( rowid == null){
				controlsQuery.userInfoDialog.modal("hide");
				showErrorDialog("请选择需要删除的用户!");
				return false;
			}
			data = crGrid.jqGrid('getRowData',rowid);
			user_id = data['usr_id'];
    		btnQuery.f7.showCallBackWarnningDialog({
    			errMsg:"是否删除选中用户的信息?",
    			callbackFn : function(data) {
    				if( data.result){
    					toolFunc.DleteUserInfoFnc( user_id );
    				}else{
    					return ;
    				}
    			}
    		})
    	},
    	f9_func : function(){
    		var user_id,
    			user_name,
    			crGrid,
    			data;
    		crGrid = controlsQuery.mainGrd.grdId;
    		$.post('jcom/checkUserAdmin', {
			}, function(Autdata) {
				if( Autdata== false){
					showErrorDialog("","你没有权限此按钮的权限!");
					return false;
				}else{
					var rowid  = crGrid.jqGrid('getGridParam','selrow');
					if( rowid == null){
						controlsQuery.userFncGroupDialog.modal("hide");
						showErrorDialog("请选择用户!");
						return false;
					}
					data = crGrid.jqGrid('getRowData',rowid);
					user_id = data['usr_id'];
					user_name = data['usr_name'];
					
					suser_id=user_id;
					suser_name=user_name;
		    		controlsQuery.userFncGroupDialog.modal({
				        backdrop:true,
				        keyboard:false,
				        show:false
			    	});
				    controlsQuery.userFncGroupDialog.unbind('shown.bs.modal');
				    btnQuery.register.unbind('click');
					$('[rel=tooltip]').tooltip({
			          placement:"bottom",
			          trigger:"focus",
			          animation:true
		        	});
			    	controlsQuery.userFncGroupDialog.unbind('shown.bs.modal');
			    	controlsQuery.userFncGroupDialog.bind('shown.bs.modal',toolFunc.showUserFncGroupDialogFnc(user_id,user_name));
			    	controlsQuery.userFncGroupDialog.modal("show");
			    	btnQuery.register.bind('click',toolFunc.AddGroupBindUserFnc);
				}
			});
			
    	}
    };
             /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.f5.click(function(){
            btnFunc.f5_func();
        });
        btnQuery.f6.click(function(){
            btnFunc.f6_func();
        });
        btnQuery.f1.click(function(){
            btnFunc.query_func();
        });
        btnQuery.f9.click(function(){
            btnFunc.f9_func();
        });
    };

     var initializationFunc = function(){
        iniGridInfo.iniUserGridInfo();
        iniGridInfo.iniFuncGridInfo();
        iniButtonAction();
        toolFunc.getUserInfoFnc();
        //toolFunc.resetJqgrid();
    };

    initializationFunc();
    function resizeFnc(){        
    	comResize(controlsQuery.W,controlsQuery.mainGrd.fatherDiv,controlsQuery.mainGrd.grdId);
    	comResize(controlsQuery.W,controlsQuery.fncGrpGrd.fatherDiv,controlsQuery.fncGrpGrd.grdId);
    	$("#userFncGroupGrd").setGridWidth((controlsQuery.W.width()-controlsQuery.fncGrpGrd.grdId.offset().left)*0.95);
//    	var offsetBottom, divWidth;                                                              
//        
//		divWidth = controlsQuery.mainGrd.fatherDiv.width();                                   
//		offsetBottom = controlsQuery.W.height() - controlsQuery.mainGrd.fatherDiv.offset().top;
//		controlsQuery.mainGrd.fatherDiv.height(offsetBottom * 0.95);                          
//		controlsQuery.mainGrd.grdId.setGridWidth(divWidth * 0.99);                   
//		controlsQuery.mainGrd.grdId.setGridHeight(offsetBottom * 0.99 - 51); 
    };                                                                                         
    resizeFnc();                                                                               
    controlsQuery.W.resize(function() {                                                         
    	resizeFnc();                                                                             
	});
});
